package com.example.mainproject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import lib.ProcessFunc;
import lib.Consts;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import classes.CookieData;
import classes.Ticket;

import com.example.mainproject.R;
import Adapters.TicketAdapter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class TicketListActivity extends Activity {

	TicketAdapter adapter;
	ArrayList<Ticket> ticketList;
	ListView lvTicket;
	CookieData cookie;
	Bundle myBundle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_ticket_list);
		lvTicket = (ListView) findViewById(R.id.tl_lvTicket);
		cookie = ProcessFunc.getCookie(getApplicationContext());
		myBundle = new Bundle();
//		adapter = new TicketAdapter(this, R.layout.ticket_row, ticketList);
		
		myAsyncTask myWebFetch = new myAsyncTask();
        myWebFetch.execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.ticket_list, menu);
		return true;
	}

	private class myAsyncTask extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			String data = "";
			try {

				data = GetTicket();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return data;
		}

		@Override
		protected void onPostExecute(String result) {
			ticketList = new ArrayList<Ticket>();
			String loc_arResponse[] = result.split("\\|");
			int loc_iResponseCode = Integer.parseInt(loc_arResponse[0]);
			if (loc_iResponseCode == Consts.RC_LOGOUT) {
				startActivity(new Intent(getApplicationContext(),
						LoginActivity.class));
				return;
			}
			if (loc_iResponseCode == Consts.RC_ERROR) {
				ProcessFunc.ShowSimpleDialog(getApplicationContext(), "Error",
						loc_arResponse[1]);
				return;
			}
			try {
				JSONArray jArray = new JSONArray(loc_arResponse[1]);
				for (int i = 0; i < jArray.length(); i++) {
					JSONObject json_data = jArray.getJSONObject(i);
					Ticket ticket = new Ticket();
					ticket.setTicketId(json_data.getInt(Consts.SDB_TICKETID));
					ticket.setTicketCode(json_data
							.getString(Consts.SDB_TICKETCODE));
					ticket.setATMId(json_data.getInt(Consts.SDB_ATMID));
					ticket.setSerialNo(json_data.getString(Consts.SDB_SERIALNO));
					ticket.setProvince(json_data.getString(Consts.SDB_PROVINCE));
//					ticket.setAddress(json_data.getString(Consts.SDB_ADDRESS));
					ticketList.add(ticket);
				}
			} catch (JSONException e) {
				Log.e("log_tag", "Error parsing data " + e.toString());
			}

			lvTicket.setAdapter(new TicketAdapter(TicketListActivity.this, R.layout.ticket_row, ticketList));

			lvTicket.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					int TicketId = ticketList.get(position).getTicketId();
					// Intent i = new Intent(getApplicationContext(),
					// TicketDetailActivity.class);
					// i.putExtra("TicketId", TicketId);
					// startActivity(i);
					myBundle.putInt("ticketID", TicketId);
					Intent intent = new Intent(TicketListActivity.this, TicketContainerActivity.class);
					intent.putExtra("ticketID", myBundle);
					startActivity(intent);
				}
			});
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected void onProgressUpdate(String... text) {
		}
	}

	private String GetTicket() {
		InputStream is = null;
		String result = "";
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Consts.MAIN_URL);

			CookieData cookie = ProcessFunc.getCookie(getApplicationContext());

			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
			nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC,
					Consts.F_TICKETLIST));
			nameValuePair.add(new BasicNameValuePair(Consts.V_USERID, cookie
					.getUserId() + ""));
			nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE, cookie
					.getCookie()));

			httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
    		is = entity.getContent();
//    		Log.d("is", is.toString());
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		try{
        	BufferedReader reader = new BufferedReader(new InputStreamReader(is,"utf-8"),16);
	    	StringBuilder sb = new StringBuilder();
	    	String line = null;
	    	while ((line = reader.readLine()) != null) {
	    		sb.append(line + "\n");
	    	}
	    	is.close();
	    	result = sb.toString();
        }
		catch(Exception e){
	    	Log.e("test", "Error converting result "+e.toString());
	    }
        return result;
	}

}
